package net.hserver.admin.monitor.queue;

import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.ioc.annotation.Value;
import cn.hserver.core.ioc.annotation.queue.QueueHandler;
import cn.hserver.core.ioc.annotation.queue.QueueListener;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import net.hserver.admin.monitor.entity.TableFile;
import net.hserver.admin.monitor.mapper.TableFileMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@QueueListener(queueName = "RE_AI")
public class ReAiQueue {


    @Value("ai.url")
    private String url;
    @Value("ai.mode")
    private String mode;
    @Value("ai.key")
    private String key;

    @Autowired
    private TableFileMapper tableFileMapper;

    @QueueHandler
    public void handle(Integer id) {
        try {
            TableFile tableFile = tableFileMapper.selectOneById(id);
            if (tableFile != null) {
                String ai = ai(tableFile.getContent());
                tableFile.setAiResult(ai);
                tableFileMapper.update(tableFile);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }


    public  String ai(String data) {
        HttpRequest httpRequest = HttpUtil.createPost(url);
        httpRequest.header("Content-Type", "application/json");
        httpRequest.header("Authorization", "Bearer " + key);

        String template = "<Content>" + data + "</Content>Content标签里是需要检查是否涉及国家保密内容，请帮我判定下 直接给出1-10级别，属于多少级别？以（安全级别:*级别）模版给出答案.";
        Map<String,Object> reqData = new HashMap<>();
        reqData.put("model",mode);
        List<Map<String,String>> reqMsgs = new ArrayList<>();
        Map<String,String> reqMsg = new HashMap<>();
        reqMsg.put("role","user");
        reqMsg.put("content",template);
        reqMsgs.add(reqMsg);
        reqData.put("messages",reqMsgs);
        HttpRequest body1 = httpRequest.body(JSONUtil.toJsonStr(reqData));
        HttpResponse execute = body1.execute();
        String body = execute.body();
        log.info("请求AI结果:{}",body);
        JSONObject entries = JSONUtil.parseObj(body);
        JSONArray jsonArray = entries.getJSONArray("choices");
        String str = jsonArray.getJSONObject(0).getJSONObject("message").getStr("content");
        if (str != null) {
            int i = str.indexOf("</think>");
            if (i != -1) {
                str = str.substring(i + 8);
            }
            return str;
        }
        return "AI检查失败";
    }

}
